import ListNode from './index.js'
// var addTwoNumbers = function (l1, l2) {
//     let p = l1;
//     let num1 = '';
//     while (p) {
//         num1 += p.val;
//         p = p.next
//     }
//     p = l2
//     let num2 = '';
//     while (p) {
//         num2 += p.val;
//         p = p.next
//     }
//     return parseInt(num1) + parseInt(num2)
// };

var addTwoNumbers = function (l1, l2) {
    let l3 = new ListNode(0);
    let p1 = l1;
    let p2 = l2;
    let p3 = l3;
    let carry = 0;
    while (p1 || p2) {
        const v1 = p1 ? p1.val : 0;
        const v2 = p2 ? p2.val : 0;
        const val = v1 + v2 + carry;
        carry = Math.floor(val / 10);
        p3.next = new ListNode(val % 10);
        if (p1) p1 = p1.next;
        if (p2) p2 = p2.next;
        p3 = p3.next
    }
    if (carry) {
        p3.next = new ListNode(carry)
    }
    return l3.next
};

let l1 = {
    val: 1,
    next: {
        val: 2,
        next: {
            val: 3,
            next: null
        }
    }
}

let l2 = {
    val: 7,
    next: {
        val: 8,
        next: {
            val: 9,
            next: null
        }
    }
}

console.log(addTwoNumbers(l1, l2))